package cn.leedsoft.and.crimeintent.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import cn.leedsoft.and.crimeintent.model.drag_and_draw.Box;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * Created by leeds on 2016/9/5 13:22.
 */
public class BoxDrawingView extends View{
    private static final String TAG = "BoxDrawingView";
    private Box mCurrentBox;
    private List<Box> mBoxes = Lists.newArrayList();
    private Paint mBoxPaint;
    private Paint mBackgroudPaint;

    public BoxDrawingView(Context context) {
        //used when creating the view in code
        super(context, null);
    }

    public BoxDrawingView(Context context, AttributeSet atts) {
        super(context, atts);//used when inflating the view from xml

        mBoxPaint = new Paint();
        mBoxPaint.setColor(0x22ff0000);//semitransparent red ARGB

        mBackgroudPaint = new Paint();
        mBackgroudPaint.setColor(0xfff8efe0);//off-white
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        PointF curr = new PointF(event.getX(), event.getY());
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i(TAG, ">>>>>ACTION_DOWN");
                mCurrentBox = new Box(curr);
                mBoxes.add(mCurrentBox);
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i(TAG, ">>>>>ACTION_MOVE");
                if(mCurrentBox != null) {
                    mCurrentBox.setCurent(curr);
                    invalidate();//会强制BoxDrawingView重新绘制自己
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.i(TAG, ">>>>>ACTION_UP");
                mCurrentBox = null;
                break;
            case MotionEvent.ACTION_CANCEL:
                Log.i(TAG, ">>>>>ACTION_CANCEL");
                mCurrentBox = null;
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPaint(mBackgroudPaint);//background

        for(Box box : mBoxes) {
            float left = Math.min(box.getOrigin().x, box.getCurent().x);
            float top = Math.min(box.getOrigin().y, box.getCurent().y);
            float right = Math.max(box.getOrigin().x, box.getCurent().x);
            float bottom = Math.max(box.getOrigin().y, box.getCurent().y);
            canvas.drawRect(left, top, right, bottom, mBoxPaint);// draw a rect
        }
    }
}
